/*
 * @Author: your name
 * @Date: 2021-02-20 11:36:23
 * @LastEditTime: 2021-02-20 18:14:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \demoe:\前端开发学习\hmtt\hm63-hmtt-wsh\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import { getLocal } from '../utils/local'
import { user } from '../api/my'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home/main'
  },
  {
    path: '/login',
    name: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/home',
    name: 'home',
    // 重定向到main页面
    redirect: 'home/main',
    component: () => import('@/views/home/home.vue'),
    children: [
      {
        path: 'main',
        name: 'main',
        component: () => import('@/views/home/main/main.vue'),
        meta: {
          needTab: true,
          needLogin: true
        }
      },
      {
        path: 'search',
        component: () => import('@/views/home/main/search.vue')
      },
      {
        path: '/home/main/details',
        component: () => import('@/views/home/main/details.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: 'searchList',
        component: () => import('@/views/home/main/searchList.vue')
      },
      {
        path: 'user',
        component: () => import('@/views/home/main/user.vue')
      },
      {
        path: 'my',
        name: 'my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          needTab: true,
          needLogin: true
        }
      },
      {
        path: '/home/my/myInfo',
        component: () => import('@/views/home/my/myInfo.vue')
      },
      {
        path: '/home/my/works',
        component: () => import('@/views/home/my/works.vue')
      },
      {
        path: '/home/my/CollectHistory',
        component: () => import('@/views/home/my/CollectHistory.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 是否需要登录才能进
  if (!to.meta.needLogin) {
    // 是否vuex没有登录,但有token
    if (!store.state.isLogin && getLocal('token')) {
      // 获取用户信息,保存至vuex
      user().then(res => {
        // console.log(res)
        store.commit('setUserInfo', res.data)
        store.commit('setIsLogin', true)
      })
    }
    next()
    // 如果vuex的isLogin为true,放行
  } else if (store.state.isLogin) {
    next()
    // 如果没有token,弹回登录页
  } else if (!getLocal('token')) {
    next('/login?redirect=' + to.fullPath)
  } else {
    user().then(res => {
      store.commit('setUserInfo', res.data)
      store.commit('setIsLogin', true)
    })
    next()
  }
})

export default router
